$(document).ready(function () {
    $(".vclass").html("v2.0.16");
})

var timghex, imghstr, bigimg = '', smallimg = '', f, bsize = 70;

var bimage = new Image();
// var imager = new Image();
var bnaturalWidth = 0, bnaturalHeight = 0;
document.getElementById('uploadimg').onchange = function () {

    $(".loading").css("top", "0%");
    $(".loadtext").html("图片处理中,请稍候");

    var img = event.target.files[0];

    // 检查能否读取图片 
    if (!img) {
        return;
    }

    if (!(img.type.indexOf('image') == 0 && img.type && /\.(?:jpg|jpeg|png|gif)$/.test(img.name))) {
        // alert('图片只能是jpg,jpeg,gif,png');
        // return;
    }

    var reader = new FileReader();

    reader.readAsDataURL(img);

    reader.onload = function (e) { // reader onload start 

        // _czc.push(['_trackEvent', '平安海报', '上传图片', '模版-'+dataindex,dataindex,'uploadimg']);

        var orientation;

        var image = new Image();

        image.src = e.target.result;

        EXIF.getData(img, function () {

            orientation = EXIF.getTag(this, 'Orientation');

            getImgData(image.src, orientation, 1, 693, img => {

                bimage.src = img;

                bigimg = img;

                bimage.onload = function () {

                    uploadimg = true;


                    bnaturalWidth = this.naturalWidth;

                    bnaturalHeight = this.naturalHeight;

                    $(".imgarea").css("background-image","url("+img+")");

                    var image = new Image();

                    image.src = img;

                    image.onload = function () {

                        $(".loading").css("top", "-100%");
                        $(".loadtext").html("LOADING");

                    }

                }

            });

        });

    }
}


function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    // reader.readAsDataURL(img);
}

function getImgData(img, orientation, s = 0, size = 300, callback) {

    var image = new Image();
    image.src = img;
    image.onload = function () {
        var degree = 0, drawWidth, drawHeight, width, height;
        drawWidth = this.naturalWidth;
        drawHeight = this.naturalHeight;

        //以下改变一下图片大小

        var maxSide = Math.max(drawWidth, drawHeight);
        var minSide = Math.min(drawWidth, drawHeight);

        // alert(123 + "__bsize:" + size);

        if (s == 0) {
            if (maxSide > size) {

                /*alert(minSide);
                minSide = minSide / maxSide * 500;*/

                minSide = minSide * (size / maxSide);
                maxSide = size;
                if (drawWidth > drawHeight) {
                    drawWidth = maxSide;
                    drawHeight = minSide;
                } else {
                    drawWidth = minSide;
                    drawHeight = maxSide;
                }
            }
        } else if (s == 1) {
            // if (minSide > size) {

            /*alert(minSide);
            minSide = minSide / maxSide * 500;*/

            maxSide = maxSide * (size / minSide);
            minSide = size;
            if (drawWidth > drawHeight) {
                drawWidth = maxSide;
                drawHeight = minSide;
            } else {
                drawWidth = minSide;
                drawHeight = maxSide;
            }
            // }
        }

        var canvas = document.createElement('canvas');

        canvas.width = width = drawWidth;

        canvas.height = height = drawHeight;

        var context = canvas.getContext('2d');

        switch (orientation) {
            //iphone横屏拍摄，此时home键在左侧
            case 3:
                degree = 180;
                drawWidth = -width;
                drawHeight = -height;
                break;
            //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
            case 6:
                canvas.width = height;
                canvas.height = width;
                degree = 90;
                drawWidth = width;
                drawHeight = -height;
                break;
            //iphone竖屏拍摄，此时home键在上方
            case 8:
                canvas.width = height;
                canvas.height = width;
                degree = 270;
                drawWidth = -width;
                drawHeight = height;
                break;
        }

        context.rotate(degree * Math.PI / 180);

        context.drawImage(this, 0, 0, drawWidth, drawHeight);

        img = canvas.toDataURL("image/png", 1);

        return callback(img);

    }

}



function cutstr(str, sti, stl) {
    var len = 0;
    str = decodeURIComponent(str);
    var key = "";
    for (var i = 0; i < str.length; i++) {
        if (i >= sti && i <= stl) {
            key = key + str[i];
        }
    }
    return key;
}
 

function getcutimg(img, callback) {

    var image = new Image();
    image.src = img;
    image.onload = function () {
        var degree = 0, drawWidth, drawHeight, width, height, ox, oy;

        // drawWidth = 120;
        // drawHeight = 120;
        drawWidth = this.naturalWidth;
        drawHeight = this.naturalHeight;


        if (drawWidth > drawHeight) {
            width = drawHeight;
            height = drawHeight;
            ox = (drawWidth - drawHeight) / 2;
            oy = 0;
        } else {
            width = drawWidth;
            height = drawWidth;
            oy = (drawHeight - drawWidth) / 2;
            ox = 0;
        }

        var canvas = document.createElement('canvas');

        canvas.width = width;

        canvas.height = height;

        var context = canvas.getContext('2d');


        //使用canvas旋转校正
        // context.rotate(degree*Math.PI/180);

        context.rotate(degree * Math.PI / 180);

        context.drawImage(this, ox, oy, width, height, 0, 0, width, height);

        img = canvas.toDataURL("image/jpeg");

        callback(img);

    }
}

var dtheighttotle = 0;

function drawText(t, x, y, w, context, fontsize, callback) {

    console.log("t.lenght:", t.length);

    // var chr = "哈哈哈哈".split("");
    // console.log(chr.length);
    if (t != '') {
        var chr = t.split("");
        var temp = "";
        var row = [];

        // var fontsize = 24;

        context.font = fontsize + "px Arial";
        // context.fillStyle = "black";

        context.fillStyle = '#FFFFFF';
        context.textBaseline = "middle";

        for (var a = 0; a < chr.length; a++) {
            if (context.measureText(temp).width < w) {
                ;
            } else {
                row.push(temp);
                temp = "";
            }
            temp += chr[a];
        }

        row.push(temp);

        for (var b = 0; b < row.length; b++) {
            context.fillText(row[b], x, y + (b + 1) * (fontsize + 8));

            dtheighttotle = y + (b + 1) * (fontsize + 8);
        }
    }

    return callback();
}


function saveAsLocalImage2() {

    // _czc.push(['_trackEvent', '平安海报', '生成海报', '模版-'+dataindex,dataindex,'SaveAsLocalImage']);

    $("#loading").fadeTo(500, 1);

    setTimeout(() => {

        $(".loadtext").html("LOADING.....");

        getqrcode(function (qrcodedata) {

            console.log("0 getqrcode");

            var qrimage = new Image();

            qrimage.src = qrcodedata;

            console.log("qrcodedata:", qrcodedata);

            qrimage.onload = function () {

                console.log("qrimage.onload");

                var image = new Image();

                image.src = backgroundimage;

                image.onload = function () {

                    $(".loadtext").html("LOADING..");

                    console.log("image.onload");

                    var that = this;

                    var degree = 0, drawWidth, drawHeight, width, height;
                    drawWidth = that.naturalWidth;
                    drawHeight = that.naturalHeight;
                    // alert(drawWidth + "-" + drawHeight);
                    var canvas = document.createElement('canvas');

                    canvas.width = width = drawWidth;

                    canvas.height = height = drawHeight;

                    var imager = new Image();

                    imager.src = err;

                    var context = canvas.getContext('2d');

                    context.fillStyle = "#ffffff";

                    context.fillRect(0,0,453,693);

                    var mh = 693, mw = 453;
                    if (bnaturalHeight / bnaturalWidth > mh / mw) {//高度超出

                        var oldbw=bnaturalWidth;
                        var oldbh=bnaturalHeight;

                        bnaturalWidth = mw;

                        bnaturalHeight = bnaturalWidth * oldbh / oldbw;

                    } else {

                        var oldbw=bnaturalWidth;
                        var oldbh=bnaturalHeight;

                        bnaturalHeight = mh;

                        bnaturalWidth = bnaturalHeight * oldbw / oldbh;
                    }

                    context.drawImage(bimage, (453 - bnaturalWidth ) /2, (693 - bnaturalHeight )/2 , bnaturalWidth, bnaturalHeight);

                    context.drawImage(that, 0, 0, drawWidth, drawHeight);



                    console.log("context.drawImage0");

                    $(".loadtext").html("LOADING.");

                    setTimeout(() => {

                        // context.drawImage(qrimage, 460, 670, 140 * 1, 140 * 1);

                        console.log("context.drawImage1");

                        $(".loadtext").html("LOADING");

                        context.drawImage(imager,335,550,85,85);

                        drawText(numbers, 37,  595, 453, context, 18,function () {

                            console.log(numbers);
                        });
``
                            drawText(data[dataindex].text0, 310, 25, 453, context, 18, function () {

                            console.log("drawText0");

                            drawText(data[dataindex].text1, 310, dtheighttotle + 1, 453, context, 18, function () {


                                console.log("drawText1");

                                var img = canvas.toDataURL("image/png", 1);

                                $(".loading").css("top", "-100%");
                                $(".loadtext").html("LOADING");
                                $("#canvasimage").attr("src", img);
                                $("#showimage").css({ "display": "flex", "opacity": "1" });

                                stoprender2 = true;

                                swiper.slideTo(2, 1100, false);//切换到生成海报


                            });

                        });

                    }, 500);


                }
                //////////////////////////////////////////////////////////////////////////////////////////////////



            }

        });


    }, 200);


}

function getqrcode(callback) {
    // 设置参数方式

    qrcode.clear();

    // $("#qrcode").html("");


    qrcode.makeCode('1');
    $("#qrcode").find("canvas").attr("id", "qrcanvas")
    $(".loadtext").html("LOADING....");
    

        var canvas = document.getElementById("qrcanvas");

        var base64Img = canvas.toDataURL();

        console.log('src:', base64Img);

        $(".loadtext").html("LOADING...");
        return callback(base64Img);

}


$(function(){
function onBridgeReady() {
WeixinJSBridge.call('hideOptionMenu');
}

if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
} else {
onBridgeReady();
}
});